package cn.org.donald.framework.controller;

import cn.org.donald.framework.constant.InfoConstant;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ： Donald
 * @date ： 2020/10/21 21:45
 * @description：
 */

@RestControllerAdvice
public class ErrorController extends BasicErrorController {

    public ErrorController() {
        super(new DefaultErrorAttributes(), new ErrorProperties());
    }

    public ErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties) {
        super(errorAttributes, errorProperties);
    }


    public ErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties, List<ErrorViewResolver> errorViewResolvers) {
        super(errorAttributes, errorProperties, errorViewResolvers);
    }


    @Override
    @RequestMapping(produces = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity<Map<String,Object>> error(HttpServletRequest request) {
        Map<String, Object> body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL));
        HttpStatus status = getStatus(request);
        Integer code = (Integer) body.get("status");
        String message = body.get("message").toString();

        if (message.contains("Authentication")){
            message = InfoConstant.UNAUTHORIZED;
            code = 401;
            status = HttpStatus.UNAUTHORIZED;

        }
        if (code == 404){
            message = InfoConstant.NOT_FOUND;
        }
        Map<String,Object> map = new LinkedHashMap<>();
        map.put("code",code);
        map.put("info",message);
        map.put("timestamp",System.currentTimeMillis());
        map.put("data","");
        return new ResponseEntity<>(map, status);
    }

}
